package com.fuhao.orderservice.controller;

import com.fuhao.orderservice.service.Impl.AsynService;
import com.fuhao.orderservice.service.OrderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RequestMapping("/api/v1/order")
@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    @RequestMapping("/save")
    //在controller接口中指定熔断后的降级方法
    @HystrixCommand(fallbackMethod = "saveOrderFail")
    public Object save(@RequestParam("userId") Integer userId , @RequestParam("productId") Integer productId){
        Map<String,Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("data", orderService.save(userId, productId));
        return map;
    }

    @Autowired
    private AsynService asynService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public Object saveOrderFail(@RequestParam("userId") Integer userId, @RequestParam("productId")Integer productId){
//       //监控报警
        //报警方法，由于发送短信耗时间，所以异步调用，@Asyn，当然也可以手动开一个线程
        asynService.bom();

        new Thread(()->{
            String saveOrderKey = "order-service";
            String sendValue = stringRedisTemplate.opsForValue().get(saveOrderKey);
            if(StringUtils.isEmpty(sendValue)){
                System.out.println("紧急短信：用户下单失败，请立刻查找原因");
                //发送一个http请求，调用短信服务

                //临时保存短信数据，用来判断20s期间是否有发送过短信
                stringRedisTemplate.opsForValue().set(saveOrderKey, "order-service-fail",20, TimeUnit.SECONDS);
            }else{
                System.out.println("已经发送短信，20秒内不发生短信");
            }
        }).start();

        Map<String,Object> map = new HashMap<>();
        map.put("code", -1);
        map.put("msg", "当前下单人数太多，请稍后尝试！");
        return map;
    }
}
